package com.dream.wukong.configcenter.client.core.converter;


import com.dream.wukong.configcenter.client.core.storage.DynamicConfig;
import com.dream.wukong.configcenter.client.core.util.ConfigConstant;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.config.DynamicStringProperty;
import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;

/***
* 描  述:  动态配置转换器
* 创建时间: 2018/5/22
*/
public class DynamicConverter {
    private static Logger logger = Logger.getLogger(DynamicConverter.class);

    /**
    * 描  述:  根据资源名称集合在本地存储相应的配置并建立key value关系,然后对key 设置变动监听
    * 参  数:sourceNames
    * 返回值: void
    * 创建时间: 2018/5/23
    */
    public static void createCallBack(List<String> sourceNames) {
        long begin = System.currentTimeMillis();
        logger.info("--------启动自动化回调机制--------");
        List<String> configSources = new ArrayList<String>();

        /////目前暂定服务端传输的数据为  sourceNamne/sourceId  的格式，所以需对sourceName进行过滤
        if(CollectionUtils.isNotEmpty(sourceNames)){
            sourceNames.forEach( sourceName -> {
                String[] strings = sourceName.split(ConfigConstant.SLASH);
                configSources.add(strings[0]);
            });
        }


        logger.info("加载配置资源:" + configSources.toString());

        logger.info("自动化回调配置资源...");
        /////将sourceName 与对应的json配置进行关联
        if(CollectionUtils.isNotEmpty(configSources)){
            configSources.forEach(configSource -> {
                ////根据key获取archaius得到的对应的value对象
                DynamicStringProperty dynamicStringProperty = DynamicPropertyFactory.getInstance().getStringProperty(
                        configSource, "");
                ///本地存储配置
                DynamicConfig.getDataSource().setConfiguration(configSource, dynamicStringProperty.getValue());
                ///将配置信息push到系统环境变量中  供spring进行获取
                ConfigConstant.pushPropertyToSystem(dynamicStringProperty.getValue());
                ///添加数据变动更新配置监听
                DynamicConfig.addCallBack(dynamicStringProperty);
            });
        }


        logger.info("--------自动化回调机制加载完毕--------耗时="
                + (System.currentTimeMillis() - begin) + "ms");
    }
}
